package com.backend.config.init;

import com.backend.common.enums.UserType;
import com.backend.modules.system.entity.SysUser;
import com.backend.modules.system.repository.SysUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
@RequiredArgsConstructor
public class InitConfiguration implements CommandLineRunner {

    private final SysUserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(String... args) {
        initAdminUser();
        printSwaggerUrl();
    }

    private void initAdminUser() {
        // 检查是否已存在管理员账号
        if (userRepository.existsByUsername("admin")) {
            log.info("管理员账号已存在，跳过初始化");
            return;
        }

        // 创建管理员账号
        SysUser admin = new SysUser();
        admin.setUsername("admin");
        admin.setPassword(passwordEncoder.encode("admin123")); // 默认密码：admin123
        admin.setRealName("系统管理员");
        admin.setUserType(UserType.ADMIN.getValue());
        admin.setPhone("13800138000");
        admin.setEmail("admin@example.com");
        admin.setStatus(true);

        userRepository.save(admin);
        log.info("管理员账号初始化成功");


    }
    /**
     * 打印 swagger 文档地址
     */
    private void printSwaggerUrl() {
        log.info("Swagger 文档地址：http://localhost:8080/api/doc.html");
    }
} 